package com.nondo.rdp.stock.endpoint.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nondo.rdp.auth.common.UserUtils;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.auth.endpoint.model.Query;
import com.nondo.rdp.core.domain.base.BaseEntity;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.stock.common.PriceUtils;
import com.nondo.rdp.stock.domain.StockChoose;
import com.nondo.rdp.stock.logic.MarketLogic;
import com.nondo.rdp.stock.service.StockChooseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 自选股票
 */
@RestController("apiStockChoose")
@RequestMapping("/api/stock/choose")
public class ChooseEndpoint {
    @Autowired
    MarketLogic marketLogic;

    @Autowired
    StockChooseService stockChooseService;

    @RequestMapping("/index")
    public View index(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<StockChoose> query) {
        View view = new View(20000, "获取数据成功");

        User user = UserUtils.getUser(request, response);

        StockChoose stockChoose = query.getData();
        stockChoose.setUser(user);
        Page<StockChoose> page = this.stockChooseService.findAll(new Page<StockChoose>(query.getPage(), query.getSize()), stockChoose);

        List list = new ArrayList();
        for (StockChoose item : page.getContent()) {
            JSONObject upData = marketLogic.getOne(item.getCode());
//            JSONArray upDataFields = upData.getJSONArray("fields");
            JSONArray upDataArray = upData.getJSONArray(item.getCode());

            //计算涨跌浮动,公式(现价-收盘价) / 收盘价
            String nowPriceString = upDataArray.get(1) + "";//固定第二个参数为当前价格
            double nowPrice = Double.valueOf(nowPriceString).doubleValue();

            String preClosePriceString = upDataArray.get(7) + "";//固定第七参数为昨日收盘价
            double preClosePrice = Double.valueOf(preClosePriceString).doubleValue();

            double doup = (nowPrice - preClosePrice) / preClosePrice;

            Map map = new HashMap();
            map.put("id", item.getId());
            map.put("code", item.getCode());
            map.put("name", item.getName());
            map.put("price", upDataArray.get(1));
            map.put("doup", PriceUtils.format(doup, 4) * 100);

            list.add(map);
        }

        //进行排序
        if (stockChoose.getSort() == 1) {//倒序
            Collections.sort(list, new Comparator<Map>() {
                public int compare(Map arg0, Map arg1) {
                    return arg1.get("doup").toString().compareTo(arg0.get("doup").toString());
                }
            });
        } else {//正序
            Collections.sort(list, new Comparator<Map>() {
                public int compare(Map arg0, Map arg1) {
                    return arg0.get("doup").toString().compareTo(arg1.get("doup").toString());
                }
            });
        }

        page.setContent(list);
        view.setData(page);

        return view;
    }

    @RequestMapping("/add")
    public View add(HttpServletRequest request, HttpServletResponse response, @RequestBody StockChoose stockChoose) {
        View view = new View(20000, "添加成功");

        User user = UserUtils.getUser(request, response);

        //判断是否已经添加了自选
        StockChoose isIn = this.stockChooseService.findByUserAndCode(user, stockChoose.getCode());
        if (isIn == null) {
            stockChoose.setUser(user);
            this.stockChooseService.save(stockChoose);
        } else if (isIn.getDelFlag().equals(BaseEntity.DEL_FLAG_DELETE)) {
            isIn.setDelFlag(BaseEntity.DEL_FLAG_NORMAL);
            this.stockChooseService.save(isIn);
        } else {
            return View.ofError("你已经添加了这支股票了");
        }

        return view;
    }

    @RequestMapping("/delete")
    public View delete(HttpServletRequest request, HttpServletResponse response, @RequestBody StockChoose stockChooseBean) {
        View view = new View(20000, "删除成功");

        User user = UserUtils.getUser(request, response);

        //只能删除自己本身的
        StockChoose stockChoose = this.stockChooseService.findByUserAndCode(user, stockChooseBean.getCode());
        if (stockChoose != null && stockChoose.getUser().getId() == user.getId()) {
            stockChoose.setDelFlag(BaseEntity.DEL_FLAG_DELETE);
            this.stockChooseService.save(stockChoose);
        }

        return view;
    }


    @RequestMapping("/check")
    public View check(HttpServletRequest request, HttpServletResponse response, @RequestBody StockChoose stockChoose) {
        View view = new View(20000, "操作成功");

        User user = UserUtils.getUser(request, response);

        //判断是否已经添加了自选
        StockChoose isIn = this.stockChooseService.findByUserAndCode(user, stockChoose.getCode());
        if (isIn == null) {
            view.setData(0);
        } else {
            view.setData(1);
        }

        return view;
    }
}